﻿<%@ WebHandler Language="C#" Class="ValidateCodeHandler" %>
using System;
using System.Drawing;
using System.Web;

public class ValidateCodeHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "image/jpg";
        CreateCheckCodeImage(context.Response);
    }

    private void CreateCheckCodeImage(HttpResponse Response)
    {
        var image = new Bitmap(40, 20);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            var random = new Random();
            var num = random.Next(1000, 9999);
            //清空图片背景色
            g.Clear(Color.Transparent);



            var font = new Font("Arial", 12);
            var brush = Brushes.Black;
            g.DrawString(num.ToString(), font, brush, 2, 2);

            var ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            Response.ContentType = "image/Png";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
